﻿//using GYCTOAManagementSystemNewApi.Controllers.PublicController;
//using GYCTOAManagementSystemNewApi.Model;
//using GYCTOAManagementSystemNewApi.Model.Enum;
//using GYCTOAManagementSystemNewApi.Model.Tool;
//using GYCTOAManagementSystemNewApi.Public;
//using Microsoft.AspNetCore.Authorization;
//using Microsoft.AspNetCore.Http;
//using Microsoft.AspNetCore.Mvc;
//using Microsoft.EntityFrameworkCore;
//using Microsoft.Extensions.Logging;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
//using System;
//using System.Collections.Generic;
//using System.Data.Entity.Validation;
//using System.Linq;
//using System.Threading.Tasks;
//using System.Transactions;

//namespace GYCTOAManagementSystemNewApi.Controllers
//{

//    [ApiExplorerSettings(IgnoreApi = true)]
//    [Route("api/[controller]")]
//    [ApiController]
//    [Authorize]
//    public class ProjectController : Controller
//    {
//        private readonly ILogger<ProjectController> _logger;
//        DBContext _db;
//        PublicTool _publictool;
//        /// <summary>
//        /// 项目备案权限码
//        /// </summary>
//        const string ProjectRecordRight = "080101";
//        /// <summary>
//        /// 计划经营部审批权限码
//        /// </summary>
//        readonly string PalnAudit = ((int)AuditRightPeopleEnum.PlanningDepart).ToString();
//        /// <summary>
//        /// 内部项目审批权限码
//        /// </summary>
//        readonly string OperateInAudit = ((int)AuditRightPeopleEnum.InternalApproval).ToString();
//        /// <summary>
//        /// 外部项目审批权限码
//        /// </summary>
//        readonly string OperateOutAudit = ((int)AuditRightPeopleEnum.ExternalApproval).ToString();
//        /// <summary>
//        /// 财务审批权限码
//        /// </summary>
//        readonly string FinanceAudit = ((int)AuditRightPeopleEnum.FinanceAccounting).ToString();
//        /// <summary>
//        /// 财务出纳签批
//        /// </summary>
//        readonly string FinanceCashier = ((int)AuditRightPeopleEnum.FinanceCashier).ToString();
//        /// <summary>
//        /// 总经理/董事长审批权限码
//        /// </summary>
//        readonly string ChairmanAudit = ((int)AuditRightPeopleEnum.Chairman).ToString();

//        public ProjectController(ILogger<ProjectController> logger, DBContext db)
//        {
//            _logger = logger;
//            _db = db;
//            _publictool = new PublicTool(_db);
//        }

//        #region 判断登录人员是否是某部门成员,或者是否是高管部门的成员，从而判断是否有操作权限
//        /// <summary>
//        /// 判断是否是部门成员,或者是否是高管部门的成员，从而判断是否有操作权限
//        /// </summary>
//        /// <param name="userId"></param>
//        /// <param name="ProjectId"></param>
//        /// <returns></returns>
//        private bool IsDepartMember(int DepartId, int userId = 0)
//        {
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            int userid = Convert.ToInt32(logid);
//            bool isMember = false;
//            if (userId == 0)
//                userId = userid;
//            Users user = _db.Users.Find(userId);
//            //if (user != null && (user.DepartmentId == DepartId || user.DepartmentId == Convert.ToInt32(AuditRightDepartEnum.SeniorManage)))
//            //    isMember = true;
//            return isMember;
//        }
//        #endregion

//        #region 项目统计接口，用于首页展示
//        /// <summary>
//        /// 获取进行中的项目
//        /// </summary>
//        /// <returns></returns>
//        [HttpPost("GetProjectOn")]
//        public JsonResult GetProjectOn()
//        {
//            var obj = _db.Project.Where(x => !x.Delete/* && x.FinishDate >= DateTime.Now).OrderByDescending(y => y.CreateDate*/).ToList();
//            return Json(obj);
//        }
//        /// <summary>
//        /// 获取已完成的项目
//        /// </summary>
//        /// <returns></returns>
//        [HttpPost("GetProjectFinish")]
//        public JsonResult GetProjectFinish()
//        {
//            var obj = _db.Project.Where(x => !x.Delete /*&& x.FinishDate < DateTime.Now).OrderByDescending(y => y.CreateDate*/).ToList();
//            return Json(obj);
//        }
//        /// <summary>
//        /// 项目详情获取
//        /// </summary>
//        /// <returns></returns>
//        [HttpPost("GetProjectDetail")]
//        public JsonResult GetProjectDetail([FromBody] dynamic formData)          
//        {
//            // (string StartDate, string EndDate, int limit, int offset, Project project, bool NoApproval)
//            string jsonstring = formData.ToString();
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(jsonstring);
//            Project project = JsonConvert.DeserializeObject<Project>(j_token["Project"].ToString());
//            int offset = Convert.ToInt32(j_token["currentPage"]);
//            int limit = Convert.ToInt32(j_token["pagesize"]);
//            bool NoApproval = Convert.ToBoolean(j_token["NoApproval"].ToString());

//            //var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            //var logid = TokenManage.GetTokenValues(author)[0].Value;
//            //var right = TokenManage.GetTokenValues(author)[2].Value;
//            //int userId = Convert.ToInt32(logid);

//            var sql = "select * from Project where 1=1 ";
//            if (project.HeadUserId != null && project.HeadUserId !="" )
//            {
//                sql += "and HeadUserId='" + project.HeadUserId + "' ";
//            }
//            //if (project.DepartmentId > 0)
//            //{
//            //    sql += "and DepartmentId='" + project.DepartmentId + "' ";
//            //}
//            if (project.Id > 0)
//            {
//                sql += "and Id='" + project.Id + "' ";
//            }
//            if (j_token["StartDate"] != null && j_token["StartDate"].ToString() != "")
//            {
//                sql += "and Date(CreateDate) >='" + j_token["StartDate"].ToString() + "' ";
//            }
//            if (j_token["EndDate"] != null && j_token["EndDate"].ToString() != "")
//            {
//                sql += "and Date(CreateDate) <='" + j_token["EndDate"].ToString() + "' ";
//            }
//            //if (project.ProjectType != 0)
//            //{
//            //    sql += "and ProjectType='" + project.ProjectType + "' ";
//            //}
//            //if (project.MemberId != null)
//            //{
//            //    var str = ArraySortToString(project.MemberId, ",");
//            //    sql += "and MemberId like'" + str + "' ";
//            //}
//            List<Project> list = new List<Project>();
//            var query = _db.Project.FromSqlRaw(sql).OrderByDescending(x => x.Id).Where(x => !x.Delete)/*.OrderByDescending(x => x.CreateDate)*/.ToList();
//            if (NoApproval)
//            {
//                foreach (var q in query)
//                {
//                    var app = _db.ProjectApproval.Where(x => x.ProjectId == q.Id).FirstOrDefault();
//                    if (app == null)
//                        list.Add(q);
//                }
//            }
//            else
//            {
//                foreach (var q in query)
//                {
//                    var app = _db.ProjectApproval.Where(x => x.ProjectId == q.Id).FirstOrDefault();
//                    if (app != null)
//                        list.Add(q);
//                }
//            }
//            list = list.OrderByDescending(x => x.OperatDate).ToList();
//            var total = list.Count;
//            var rows = list.Take(limit * offset).Skip(limit * (offset - 1)).ToList();
//            //var ret = JsonConvert.SerializeObject(rows, setting);
//            return Json(new { code = 0, msg = "", count = total, data = rows });
//        }
//        /// <summary>
//        /// 新建项目方案
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("AddProjectRecord")]
//        public JsonResult AddProjectRecord([FromBody] dynamic formData)          
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>( formData.ToString());
//            Project project = JsonConvert.DeserializeObject<Project>(j_token["Project"].ToString());

//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            var right = TokenManage.GetTokenValues(author)[2].Value;
//            int userId = Convert.ToInt32(logid);

//            var flag = false;
//            project.OperatId = userId;
//            project.OperatDate = DateTime.Now;

//            //if (project.ProjectType != (int)ProjectTypeEnum.ConstructionProduction)
//            //{
//            //    project.ManagementDate = project.OperatDate;
//            //}
//            try
//            {
//                _db.Project.Add(project);
//                flag = _db.SaveChanges() > 0 ? true : false;
//            }
//            catch (DbEntityValidationException dbEx)
//            {
//                return Json(flag);
//            }
//            return Json(flag);
//        }
//        #endregion

//        #region 项目立项阶段
//        /// <summary>
//        /// 项目立项阶段数据获取
//        /// </summary>
//        /// <param name="id"></param>
//        /// <returns></returns>
//        [HttpGet("GetAllRecordData")]
//        public JsonResult GetAllRecordData(int id)
//        {
//            //JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            //int id = Convert.ToInt32(j_token["id"].ToString());
//            ProjectApproval projectApproval = _db.ProjectApproval.Where(x => x.ProjectId == id).FirstOrDefault();
//            ProjectTask projectTask = _db.ProjectTask.Where(x => x.ProjectId == id).FirstOrDefault();
//            ProjectCapitalPlan projectCapitalPlanOne = _db.ProjectCapitalPlan.Where(x => x.ProjectId == id && x.Type == 1).FirstOrDefault();
//            ProjectCapitalPlan projectCapitalPlanTwo = _db.ProjectCapitalPlan.Where(x => x.ProjectId == id && x.Type == 2).FirstOrDefault();
//            List<ProjectPeople> projectPeople = _db.ProjectPeople.Where(x => x.ProjectId == id && !x.Delete && (x.DataSources == (int)ProjectPeopleDataSourceEnum.Approval || x.DataSources == (int)ProjectPeopleDataSourceEnum.Task)).ToList();
//            return Json(new { projectApproval, projectTask, projectCapitalPlanOne, projectCapitalPlanTwo, projectPeople });
//        }
//        /// <summary>
//        /// 备案信息修改
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateProjectRecord")]
//        public JsonResult UpdateProjectRecord([FromBody] dynamic formData)           
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            Project project = JsonConvert.DeserializeObject<Project>(j_token["Project"].ToString());
//            _db.Project.Update(project);
//            Message mess = new Message();
//            mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//            mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
//            return Json(mess);
//        }
//        /// <summary>
//        /// 新增或修改项目申请表
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateProjectApproval")]
//        public JsonResult UpdateProjectApproval([FromBody] dynamic formData)
//        {
//            // (Project project, ProjectApproval projectApproval, List<ProjectPeople> ProjectPeople)
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            Project project = JsonConvert.DeserializeObject<Project>(j_token["project"].ToString());
//            ProjectApproval projectApproval = JsonConvert.DeserializeObject<ProjectApproval>(j_token["ProjectApproval"].ToString());
//            List<ProjectPeople> ProjectPeople = JsonConvert.DeserializeObject<List<ProjectPeople>>(j_token["ProjectPeople"].ToString());

//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            var right = TokenManage.GetTokenValues(author)[2].Value;
//            int userId = Convert.ToInt32(logid);

//            PublicMethodApiController pubc = new PublicMethodApiController(_db);

//            Project pro = _db.Project.Where(x => x.Id == projectApproval.ProjectId).FirstOrDefault();
//            Message mess = new Message();
//            using (var scope = new TransactionScope())
//            {
//                if (!pubc.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userId))
//                {
//                    mess.IsSuccess = false;
//                    mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                    return Json(mess);
//                }
//                //项目备案信息
//                //pro.CreateDate = project.CreateDate;
//                //pro.FinishDate = project.FinishDate;
//                //pro.ContractAmount = project.ContractAmount;
//                //pro.ContractId = project.ContractId;
//                //pro.Bond = project.Bond;
//                projectApproval.OperatDate = DateTime.Now;
//                projectApproval.OperatId = userId;
//                //id为0代表是新增数据，反之则为修改数据
//                if (projectApproval.Id == 0)
//                {
//                    //项目申请表
//                    _db.ProjectApproval.Add(projectApproval);
//                }
//                else
//                {
//                    //项目申请表
//                    ProjectApproval appro = _db.ProjectApproval.Where(x => x.Id == projectApproval.Id).FirstOrDefault();
//                    appro.AcceptancIndex = projectApproval.AcceptancIndex;
//                    appro.ManMachine = projectApproval.ManMachine;
//                    appro.OverviewOfExpected = projectApproval.OverviewOfExpected;
//                    appro.BuildUnit = projectApproval.BuildUnit;
//                    appro.DesignUnit = projectApproval.DesignUnit;
//                    appro.ReconnaissanceUnit = projectApproval.ReconnaissanceUnit;
//                    appro.ConstructionControlUnit = projectApproval.ConstructionControlUnit;
//                    appro.ConstructionUnit = projectApproval.ConstructionUnit;
//                    appro.QualityInspectionUnit = projectApproval.QualityInspectionUnit;
//                    appro.BuildPlace = projectApproval.BuildPlace;
//                    appro.BaseType = projectApproval.BaseType;
//                    appro.OtherUnit = projectApproval.OtherUnit;
//                    appro.ProjectInstructorAmount = projectApproval.ProjectInstructorAmount;
//                    appro.ProjectLeaderAmount = projectApproval.ProjectLeaderAmount;
//                    appro.OtherProjectManAmount = projectApproval.OtherProjectManAmount;
//                    appro.ArtisanAmount = projectApproval.ArtisanAmount;
//                    appro.ArtisanWork = projectApproval.ArtisanWork;
//                    appro.ConstructionerAmount = projectApproval.ConstructionerAmount;
//                    appro.ConstructionerWork = projectApproval.ConstructionerWork;
//                    appro.OutsideStaffAmount = projectApproval.OutsideStaffAmount;
//                    appro.OutsideStaffWork = projectApproval.OutsideStaffWork;
//                    appro.OutputValue = projectApproval.OutputValue;
//                    appro.BusinessRisk = projectApproval.BusinessRisk;
//                    appro.ProductionRisk = projectApproval.ProductionRisk;
//                    appro.OtherRisk = projectApproval.OtherRisk;
//                    appro.OperatId = projectApproval.OperatId;
//                    appro.OperatDate = projectApproval.OperatDate;
//                    //申请表中的人员配置
//                    var peoples = _db.ProjectPeople.Where(x => x.ProjectId == pro.Id && x.DataSources == (int)ProjectPeopleDataSourceEnum.Approval).ToList();
//                    foreach (var p in peoples)
//                    {
//                        _db.ProjectPeople.Remove(p);
//                    }
//                }
//                //添加人员配置
//                if (ProjectPeople != null)
//                {
//                    foreach (var peo in ProjectPeople)
//                    {
//                        var user = _db.Users.Where(x => x.Id == peo.Userid).FirstOrDefault();
//                        peo.ProjectId = pro.Id;
//                        //peo.DepartmentId = user.DepartmentId;
//                        peo.RoleId = user.RoleId;
//                        peo.UserName = user.UserName;
//                        peo.DataSources = (int)ProjectPeopleDataSourceEnum.Approval;
//                        peo.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
//                        peo.OperatDate = DateTime.Now;
//                        peo.OperatId = userId;
//                        _db.ProjectPeople.Add(peo);
//                    }
//                }
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
//            return Json(mess);
//        }
//        /// <summary>
//        /// 新增或修改项目任务书
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateProjectTask")]
//        public JsonResult UpdateProjectTask([FromBody] dynamic formData)
//        {
//            //Project project, ProjectTask projectTask, List<ProjectPeople> ProjectPeople)
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var project = JsonConvert.DeserializeObject<Project>(jsondata["project"].ToString());
//            var projectTask = JsonConvert.DeserializeObject<ProjectTask>(jsondata["projectTask"].ToString());
//            var ProjectPeople = JsonConvert.DeserializeObject<List<ProjectPeople>>(jsondata["ProjectPeople"].ToString());
//            Project pro = _db.Project.Where(x => x.Id == projectTask.ProjectId).FirstOrDefault();
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);

//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            Message mess = new Message();
//            using (var scope = new TransactionScope())
//            {
//                if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
//                {
//                    mess.IsSuccess = false;
//                    mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                    return new JsonResult(new { msg = mess });
//                }
//                pro.HeadUserId = project.HeadUserId;
//                projectTask.OperatDate = DateTime.Now;
//                projectTask.OperatId = userid;
//                if (projectTask.Id == 0)
//                {
//                    _db.ProjectTask.Add(projectTask);
//                }
//                else
//                {
//                    //项目申请表
//                    ProjectTask task = _db.ProjectTask.Where(x => x.Id == projectTask.Id).FirstOrDefault();
//                    task.HeadUserWork = projectTask.HeadUserWork;
//                    task.MaterialManager = projectTask.MaterialManager;
//                    task.MaterialManagerWork = projectTask.MaterialManagerWork;
//                    task.Bookkeeper = projectTask.Bookkeeper;
//                    task.BookkeeperWork = projectTask.BookkeeperWork;
//                    task.SecurityOfficer = projectTask.SecurityOfficer;
//                    task.SecurityOfficerWork = projectTask.SecurityOfficerWork;
//                    task.Technician = projectTask.Technician;
//                    task.TechnicianWork = projectTask.TechnicianWork;
//                    task.Constructors = projectTask.Constructors;
//                    task.ConstructionerWork = projectTask.ConstructionerWork;
//                    task.OutsideStaffAmount = projectTask.OutsideStaffAmount;
//                    task.OutsideStaffWork = projectTask.OutsideStaffWork;
//                    task.PlannedCapital = projectTask.PlannedCapital;
//                    task.ApprovedFunds = projectTask.ApprovedFunds;
//                    task.Fudonglv = projectTask.Fudonglv;
//                    task.FirstStageProcedure = projectTask.FirstStageProcedure;
//                    task.FirstStageEffect = projectTask.FirstStageEffect;
//                    task.SecondStageProcedure = projectTask.SecondStageProcedure;
//                    task.SecondStageEffect = projectTask.SecondStageEffect;
//                    task.ThirdStageProcedure = projectTask.ThirdStageProcedure;
//                    task.ThirdStageEffect = projectTask.ThirdStageEffect;
//                    task.FourthStageProcedure = projectTask.FourthStageProcedure;
//                    task.FourthStageEffect = projectTask.FourthStageEffect;
//                    task.OperatId = projectTask.OperatId;
//                    task.OperatDate = projectTask.OperatDate;
//                }
//                if (ProjectPeople.Count>0) 
//                {
//                    //申请表中的人员配置
//                    var peoples = _db.ProjectPeople.Where(x => x.ProjectId == pro.Id && x.DataSources == (int)ProjectPeopleDataSourceEnum.Task).ToList();
//                    foreach (var p in peoples)
//                    {
//                        _db.ProjectPeople.Remove(p);
//                    }
//                }
//                //添加人员配置
//                foreach (var peo in ProjectPeople)
//                {
//                    var user = _db.Users.Where(x => x.Id == peo.Userid).FirstOrDefault();
//                    peo.ProjectId = pro.Id;
//                    //peo.DepartmentId = user.DepartmentId;
//                    peo.RoleId = user.RoleId;
//                    peo.UserName = user.UserName;
//                    peo.DataSources = (int)ProjectPeopleDataSourceEnum.Task;
//                    peo.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
//                    peo.OperatDate = DateTime.Now;
//                    peo.OperatId = userid;
//                    _db.ProjectPeople.Add(peo);
//                }
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
//            return Json(mess);
//        }
//        /// <summary>
//        /// 新增或修改项目资金计划表
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateProjectCapitalPlan")]
//        public JsonResult UpdateProjectCapitalPlan([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            ProjectCapitalPlan projectCapitalPlan = JsonConvert.DeserializeObject<ProjectCapitalPlan>(jsondata["projectCapitalPlan"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
//            Message mess = new Message();
//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            using (var scope = new TransactionScope())
//            {
//                if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
//                {
//                    mess.IsSuccess = false;
//                    mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                    return Json(mess);
//                }
//                projectCapitalPlan.OperatDate = DateTime.Now;
//                projectCapitalPlan.OperatId = userid;
//                //id为0代表是新增数据，反之则为修改数据
//                if (projectCapitalPlan.Id == 0)
//                {
//                    _db.ProjectCapitalPlan.Add(projectCapitalPlan);
//                }
//                else
//                {
//                    //项目申请表
//                    ProjectCapitalPlan Capital = _db.ProjectCapitalPlan.Where(x => x.Id == projectCapitalPlan.Id).FirstOrDefault();
//                    Capital.MaterialCost = projectCapitalPlan.MaterialCost;
//                    Capital.MaterialCostDes = projectCapitalPlan.MaterialCostDes;
//                    Capital.NewTools = projectCapitalPlan.NewTools;
//                    Capital.NewToolsDes = projectCapitalPlan.NewToolsDes;
//                    Capital.NewDevice = projectCapitalPlan.NewDevice;
//                    Capital.NewDeviceDes = projectCapitalPlan.NewDeviceDes;
//                    Capital.OfficeExpenses = projectCapitalPlan.OfficeExpenses;
//                    Capital.OfficeExpensesDes = projectCapitalPlan.OfficeExpensesDes;
//                    Capital.TravelExpenses = projectCapitalPlan.TravelExpenses;
//                    Capital.TravelExpensesDes = projectCapitalPlan.TravelExpensesDes;
//                    Capital.LivingExpenses = projectCapitalPlan.LivingExpenses;
//                    Capital.LivingExpensesType = projectCapitalPlan.LivingExpensesType;
//                    Capital.HotelExpense = projectCapitalPlan.HotelExpense;
//                    Capital.HotelExpenseType = projectCapitalPlan.HotelExpenseType;
//                    Capital.TrainingFee = projectCapitalPlan.TrainingFee;
//                    Capital.TrainingFeeDes = projectCapitalPlan.TrainingFeeDes;
//                    Capital.EquipmentRentalFee = projectCapitalPlan.EquipmentRentalFee;
//                    Capital.EquipmentRentalFeeDes = projectCapitalPlan.EquipmentRentalFeeDes;
//                    Capital.EquipmentFuelCost = projectCapitalPlan.EquipmentFuelCost;
//                    Capital.EquipmentFuelCostDes = projectCapitalPlan.EquipmentFuelCostDes;
//                    Capital.MaintenanceCost = projectCapitalPlan.MaintenanceCost;
//                    Capital.MaintenanceCostDes = projectCapitalPlan.MaintenanceCostDes;
//                    Capital.BusinessEntertainment = projectCapitalPlan.BusinessEntertainment;
//                    Capital.BusinessEntertainmentDes = projectCapitalPlan.BusinessEntertainmentDes;
//                    Capital.LaborCost = projectCapitalPlan.LaborCost;
//                    Capital.LaborCostDes = projectCapitalPlan.LaborCostDes;
//                    Capital.LabourInsuranceArticles = projectCapitalPlan.LabourInsuranceArticles;
//                    Capital.LabourInsuranceArticlesDes = projectCapitalPlan.LabourInsuranceArticlesDes;
//                    Capital.Freight = projectCapitalPlan.Freight;
//                    Capital.FreightDes = projectCapitalPlan.FreightDes;
//                    Capital.ConsultationFee = projectCapitalPlan.ConsultationFee;
//                    Capital.ConsultationFeeDes = projectCapitalPlan.ConsultationFeeDes;
//                    Capital.OtherExpenses = projectCapitalPlan.OtherExpenses;
//                    Capital.OtherExpensesDes = projectCapitalPlan.OtherExpensesDes;
//                    Capital.OperatId = projectCapitalPlan.OperatId;
//                    Capital.OperatDate = projectCapitalPlan.OperatDate;
//                }
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
//            return Json(mess);
//        }
//        #endregion

//        #region 项目前期准备视图
//        /// <summary>
//        /// 获取准备阶段的所有数据
//        /// </summary>
//        /// <param name="id"></param>
//        /// <returns></returns>
//        [HttpPost("GetAllPrepareData")]
//        public JsonResult GetAllPrepareData([FromBody] dynamic formData)
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            int id = Convert.ToInt32(j_token["id"].ToString());
//            List<ProjectWorkPlan> projectWorkPlans = _db.ProjectWorkPlan.Where(x => x.ProjectId == id && !x.Delete).ToList();
//            List<ProjectDevice> projectDevices = _db.ProjectDevice.Where(x => x.ProjectId == id && !x.Delete && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost).ToList();
//            List<ProjectPeople> projectPeople = _db.ProjectPeople.Where(x => x.ProjectId == id && !x.Delete && x.DataSources == (int)ProjectPeopleDataSourceEnum.PeoplePlan && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost).ToList();
//            List<Files> planFiles = PublicTool.GetFileInfo("施工方案", "2\\" + id + "\\4");
//            List<Files> applicationFiles = PublicTool.GetFileInfo("项目开工申请报告", "2\\" + id + "\\8");
//            List<Files> otherFiles = PublicTool.GetFileInfo("其他", "2\\" + id + "\\256");

//            return Json(new { projectWorkPlans, projectDevices, projectPeople, planFiles, applicationFiles, otherFiles });
//        }
//        /// <summary>
//        /// 新增项目工作实施计划表
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("AddProjectWorkPlan")]
//        public JsonResult AddProjectWorkPlan([FromBody] dynamic formData)          
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            ProjectWorkPlan projectWorkPlan = JsonConvert.DeserializeObject<ProjectWorkPlan>(j_token["projectWorkPlan"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            // var right = TokenManage.GetTokenValues(author)[2].Value;
//            int userId = Convert.ToInt32(logid);
//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            Message mess = new Message();
//            using (var scope = new TransactionScope())
//            {
//                if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author , userId))
//                {
//                    mess.IsSuccess = false;
//                    mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                    return Json(new { result = mess, projectWorkPlan = "" });
//                }
//                projectWorkPlan.OperatDate = DateTime.Now;
//                projectWorkPlan.OperatId = userId;
//                _db.ProjectWorkPlan.Add(projectWorkPlan);
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
//            return Json(new { result = mess , projectWorkPlan = projectWorkPlan });
//        }
//        /// <summary>
//        /// 修改项目工作实施计划表
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateProjectWorkPlan")]
//        public JsonResult UpdateProjectWorkPlan([FromBody] dynamic formData)
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            ProjectWorkPlan projectWorkPlan = JsonConvert.DeserializeObject<ProjectWorkPlan>(j_token["projectWorkPlan"].ToString());

//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            // var right = TokenManage.GetTokenValues(author)[2].Value;
//            int userid = Convert.ToInt32(logid);
//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            Message mess = new Message();
//            using (var scope = new TransactionScope())
//            {
//                if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
//                {
//                    mess.IsSuccess = false;
//                    mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                    return Json(mess);
//                }
//                //项目申请表
//                ProjectWorkPlan workPlan = _db.ProjectWorkPlan.Where(x => x.Id == projectWorkPlan.Id && !x.Delete).FirstOrDefault();
//                workPlan.Price = projectWorkPlan.Price;
//                workPlan.EngineState = projectWorkPlan.EngineState;
//                workPlan.ConstructionProcedure = projectWorkPlan.ConstructionProcedure;
//                workPlan.ConstructionContents = projectWorkPlan.ConstructionContents;
//                workPlan.TotalQuantity = projectWorkPlan.TotalQuantity;
//                workPlan.PlanStartDate = projectWorkPlan.PlanStartDate;
//                workPlan.PlanEndDate = projectWorkPlan.PlanEndDate;
//                workPlan.Planner = projectWorkPlan.Planner;
//                workPlan.PlanningMaterials = projectWorkPlan.PlanningMaterials;
//                workPlan.PlanningMachinery = projectWorkPlan.PlanningMachinery;
//                workPlan.Remark = projectWorkPlan.Remark;
//                workPlan.Unit = projectWorkPlan.Unit;
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
//            return Json(mess);
//        }
//        /// <summary>
//        /// 删除项目工作实施计划表
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("DeleteProjectWorkPlan")]
//        public JsonResult DeleteProjectWorkPlan([FromBody] dynamic formData)
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            int id = Convert.ToInt32(j_token["id"].ToString());

//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            int userid = Convert.ToInt32(logid);

//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            Message mess = new Message();
//            if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
//            {
//                mess.IsSuccess = false;
//                mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                return Json(mess);
//            }
//            var data = _db.ProjectWorkPlan.Where(x => x.Id == id).FirstOrDefault();
//            data.Delete = true;
//            data.OperatId = userid;
//            data.OperatDate = DateTime.Now;
//            mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//            mess.Msg = mess.IsSuccess ? "删除成功" : "删除失败";
//            return Json(mess);
//        }
//        /// <summary>
//        /// 新增项目人员配置信息
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("AddProjectPeople")]
//        public JsonResult AddProjectPeople([FromBody] dynamic formData)
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            ProjectPeople projectPeople = JsonConvert.DeserializeObject<ProjectPeople>(j_token["projectPeoplePage"].ToString());

//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            int userid = Convert.ToInt32(logid);

//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            Message mess = new Message();
//            using (var scope = new TransactionScope())
//            {
//                if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
//                {
//                    mess.IsSuccess = false;
//                    mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                    return Json(mess);
//                }
//                projectPeople.OperatDate = DateTime.Now;
//                projectPeople.OperatId = userid;
//                projectPeople.DataSources = (int)ProjectPeopleDataSourceEnum.PeoplePlan;
//                if (projectPeople.Type == (int)ProjectPeopleTypeEnum.FullTime)
//                {
//                    var user = _db.Users.Where(x => x.Id == projectPeople.Userid).FirstOrDefault();
//                    //projectPeople.DepartmentId = user.DepartmentId;
//                    projectPeople.RoleId = user.RoleId;
//                    projectPeople.UserName = user.UserName;
//                }
//                projectPeople.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
//                projectPeople.OperatDate = DateTime.Now;
//                projectPeople.OperatId = userid;
//                _db.ProjectPeople.Add(projectPeople);
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
//            return Json(new { result = mess, projectPeople = projectPeople });
//        }
//        /// <summary>
//        /// 修改项目人员配置信息
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateProjectPeople")]
//        public JsonResult UpdateProjectPeople([FromBody] dynamic formData)
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            ProjectPeople projectPeople = JsonConvert.DeserializeObject<ProjectPeople>(j_token["projectPeople"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            Message mess = new Message();
//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            using (var scope = new TransactionScope())
//            {
//                if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author))
//                {
//                    mess.IsSuccess = false;
//                    mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                    return Json(mess);
//                }
//                //项目申请表
//                ProjectPeople people = _db.ProjectPeople.Where(x => x.Id == projectPeople.Id && !x.Delete).FirstOrDefault();
//                people.Type = projectPeople.Type;
//                if (people.Type == (int)ProjectPeopleTypeEnum.FullTime)
//                {
//                    var user = _db.Users.Where(x => x.Id == projectPeople.Userid).FirstOrDefault();
//                    //people.DepartmentId = user.DepartmentId;
//                    people.RoleId = user.RoleId;
//                    people.UserName = user.UserName;
//                }
//                else if (people.Type == (int)ProjectPeopleTypeEnum.PartTime)
//                {
//                    people.UserName = projectPeople.UserName;
//                    people.Age = projectPeople.Age;
//                    people.LaborCost = projectPeople.LaborCost;
//                }
//                people.Skill = projectPeople.Skill;
//                people.WorkContent = projectPeople.WorkContent;
//                people.WorkCycle = projectPeople.WorkCycle;
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
//            return Json(mess);
//        }
//        /// <summary>
//        /// 删除项目人员配置信息
//        /// </summary>
//        /// <param name="project"></param>
//        /// <returns></returns>
//        [HttpPost("DeleteProjectPeople")]
//        public JsonResult DeleteProjectPeople([FromBody] dynamic formData)
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            int id = Convert.ToInt32(j_token["id"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            int userid = Convert.ToInt32(logid);
//            Message mess = new Message();
//            PublicMethodApiController pub = new PublicMethodApiController(_db);
//            if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
//            {
//                mess.IsSuccess = false;
//                mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
//                return Json(mess);
//            }
//            var data = _db.ProjectPeople.Where(x => x.Id == id).FirstOrDefault();
//            data.Delete = true;
//            data.OperatId = userid;
//            data.OperatDate = DateTime.Now;
//            mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//            mess.Msg = mess.IsSuccess ? "删除成功" : "删除失败";
//            return Json(mess);
//        }
//        /// <summary>
//        /// 添加项目人员和设备调动记录
//        /// </summary>
//        /// <returns></returns>
//        [HttpPost("AddProjectPeopleTransferData")]
//        public JsonResult AddProjectPeopleTransferData([FromBody] dynamic formData)
//        {
//            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//            ProjectPeopleDeviceTransfer projectPeopleDeviceTransfer = JsonConvert.DeserializeObject<ProjectPeopleDeviceTransfer>(j_token["projectPeopleDeviceTransfer"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            int userid = Convert.ToInt32(logid);

//            Message mess = new Message();
//            using (var scope = new TransactionScope())
//            {
//                projectPeopleDeviceTransfer.ApplyDate = DateTime.Now;
//                projectPeopleDeviceTransfer.OperatDate = DateTime.Now;
//                projectPeopleDeviceTransfer.OperatId = userid;
//                _db.ProjectPeopleDeviceTransfer.Add(projectPeopleDeviceTransfer);
//                mess.IsSuccess = _db.SaveChanges() > 0 ? true : false;
//                scope.Complete();
//            }
//            mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
//            return Json(mess);
//        }
//        #endregion

//        #region 项目日常管理阶段
//        /// <summary>
//        /// 判断是否有项目负责人权限
//        /// </summary>
//        /// <param name="userId"></param>
//        /// <param name="ProjectId"></param>
//        /// <returns></returns>
//        private bool IsProjectHeadUser(int userId,string author, int ProjectId)
//        {
//            var logid = TokenManage.GetTokenValues(author)[0].Value;
//            int userid = Convert.ToInt32(logid);
//            bool isHeadUser = false;
//            if (userId == 0) userId = userid;
//            Project project = _db.Project.Find(ProjectId);
//            if (project != null && Convert.ToInt32(project.HeadUserId) == userId)
//                isHeadUser = true;
//            return isHeadUser;
//        }
//        /// <summary>
//        /// 获取准备阶段的所有数据
//        /// </summary>
//        /// <param name="id"></param>
//        /// <returns></returns>
//        //[HttpPost("GetAllDailyManageData")]
//        //public JsonResult GetAllDailyManageData([FromBody] dynamic formData)
//        //{
//        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
//        //    int id = Convert.ToInt32(j_token["id"].ToString());
//        //    var project = _db.Project.Where(l => l.Id == id).FirstOrDefault();
//        //    List<ProjectExpenseDetail> projectExpenseDetail = _db.ProjectExpenseDetail.Where(x => x.ProjectId == id && !x.Delete).ToList();
//        //    List<ProjectJournal> projectJournal = _db.ProjectJournal.Where(x => x.ProjectId == id && !x.Delete).OrderByDescending(y => y.JournalDate).ToList();
//        //    //if (project.ProjectType == (int)ProjectTypeEnum.ConstructionProduction)
//        //    //{
//        //    //    //List<ProjectWorkProgress> projectWorkProgress = db.ProjectWorkProgress.Where(x => x.ProjectId == id && !x.Delete).ToList();
//        //    //    //List<ProjectDeviceUseRecord> projectDeviceUseRecord = db.ProjectDeviceUseRecord.Where(x => x.ProjectId == id && !x.Delete).ToList();
//        //    //    //List<ProjectToolUseRecord> projectToolUseRecord = db.ProjectToolUseRecord.Where(x => x.ProjectId == id && !x.Delete).ToList();
//        //    //    //List<ProjectOutputMeasure> projectOutputMeasure = db.ProjectOutputMeasure.Where(x => x.ProjectId == id && !x.Delete).ToList();
//        //    //    //return Json(new { project, projectWorkProgress, projectDeviceUseRecord, projectToolUseRecord, projectJournal, projectOutputMeasure, projectExpenseDetail }, JsonRequestBehavior.DenyGet);
//        //    //    return Json(new { project, projectJournal, projectExpenseDetail });
//        //    //}
//        //    //else
//        //    //{
//        //    //    List<ProjectPeople> projectPeople = _db.ProjectPeople.Where(x => x.ProjectId == id && !x.Delete && x.DataSources == (int)ProjectPeopleDataSourceEnum.DesignDev).ToList();
//        //    //    ProjectDesignDevReview projectDesignDevReview = _db.ProjectDesignDevReview.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
//        //    //    ProjectReviewTrack projectReviewTrack = _db.ProjectReviewTrack.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
//        //    //    ProjectChangeApply projectChangeApply = _db.ProjectChangeApply.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
//        //    //    ProjectChangeNotice projectChangeNotice = _db.ProjectChangeNotice.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
//        //    //    ProjectEndApply projectEndApply = _db.ProjectEndApply.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
//        //    //    ProjectEndNotice projectEndNotice = _db.ProjectEndNotice.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
//        //    //    return Json(new { project, projectJournal, projectExpenseDetail, projectPeople, projectDesignDevReview, projectReviewTrack, projectChangeApply, projectChangeNotice, projectEndApply, projectEndNotice });
//        //    //}
//        //}
//        #endregion
//    }
//}
